<template>
  <!-- 企业基本信息 -->
  <div class="app-container horizontal">
    <el-row :gutter="40">
      <el-col v-show="fold" class="headRowClass" :span="4" :xs="24">
        <!-- 左侧企业列表城市菜单树 -->
        <div class="head-container">
          <el-input
            v-model="cityName"
            placeholder="请输入城市名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
          />
        </div>
        <div class="head-container">
          <el-tree
            ref="tree"
            :data="cityOptions"
            :props="defaultProps"
            node-key="label"
            :expand-on-click-node="false"
            :default-expand-all="false"
            :filter-node-method="filterNode"
            :highlight-current="currentColor"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="fold === true?20:24" :xs="24" class="right-content">
        <el-col v-if="fold" :span="1">
          <el-row class="treeStyle el-tree-arrow">
            <i class="el-icon-arrow-left" @click="fold = false" />
          </el-row>
        </el-col>
        <el-col v-if="!fold" :span="1">
          <el-row type="flex" justify="center" class="treeStyle2 el-tree-arrow">
            <i class="el-icon-arrow-right" @click="fold = true" />
          </el-row>
        </el-col>
        <div class="form-container">
          <el-form
            ref="topForm"
            :inline="true"
            label-width="80px"
            :model="filters"
            class="selectFrom"
            style="text-align:left"
          >
            <el-row>
              <el-form-item label="企业名称" prop="name">
                <el-input v-model="filters.name" size="small" clearable placeholder="请输入企业名称" />
              </el-form-item>
              <el-form-item label="企业状态" prop="status">
                <el-select
                  v-model="filters.status"
                  placeholder="请选择企业状态"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="dict in statusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="创建时间" prop="dateRange">
                <el-date-picker
                  v-model="dateRange"
                  size="small"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width:225px"
                  clearable
                />
              </el-form-item>
              <!-- <el-form-item label="企业类型" prop="enterpriseType">
                <el-select
                  v-model="filters.enterpriseType"
                  placeholder="请选择企业类型"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="dict in enterpriseTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item> -->
              <!--              <el-form-item label="企业法人" prop="legalperson">-->
              <!--                <el-input v-model="filters.legalperson" size="small" clearable placeholder="请输入企业法人" />-->
              <!--              </el-form-item>-->
              <!--              <el-form-item>-->
              <!--                <slot name="label">-->
              <!--                  <i class="highLevelStyle" :class="highLevelSet===true?'el-icon-arrow-up':'el-icon-arrow-down'" @click="highLevelSet = !highLevelSet" />-->
              <!--                </slot>-->
              <!--              </el-form-item>-->
            </el-row>
            <!-- 高级设置一栏 start -->
            <!-- <high-level-setting v-if="highLevelSet" :parent-to-child="highLevelSettingData" @sendValueToParent="getValueFromChild"></high-level-setting> -->
            <!--            <el-row v-if="highLevelSet">-->
            <!--            </el-row>-->
          </el-form>
        </div>
        <el-row :gutter="10" class="button-wrap">
          <el-col :span="1.5">
            <el-button v-clickForbidden icon="el-icon-search" size="middle" @click="handleQuery">搜索</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-clickForbidden icon="el-icon-refresh" size="middle" @click="resetQuery">重置</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:sysEnterprise:add']"
              size="middle"
              icon="el-icon-plus"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:sysEnterprise:edit']" size="middle" :disabled="isAmend" icon="el-icon-edit" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:sysEnterprise:remove']" size="middle" :disabled="isAmend" icon="el-icon-delete" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col v-hasPermi="['system:sysEnterprise:edit']" :span="1.5">
            <el-button v-show="status === '0'" size="middle" :disabled="isStatus" icon="el-icon-star-off" @click="handleStatusChange">
              停用
            </el-button>
          </el-col>
          <el-col v-hasPermi="['system:sysEnterprise:edit']" :span="1.5">
            <el-button v-show="status === '1'" size="middle" :disabled="isStatus" icon="el-icon-star-on" @click="handleStatusChange">
              启用
            </el-button>
          </el-col>
        </el-row>
        <!-- 表格展示start -->
        <el-table
          ref="multipleTable"
          v-loading="tableLoading"
          :data="tableData"
          class="table-list"
          stripe
          :class="highLevelSet===true ? (needTagsView===true ? 'el-body-page-roll-tag-height' : 'el-body-page-roll-height') :
            (needTagsView===true ? 'el-body-page-roll-tag' : 'el-body-page-roll')"
          style="width:100%;"
          :row-style="rowColor"
          @selection-change="handleSelectionChange"
          @row-click="rowChecked"
        >
          <el-table-column type="selection" width="38" align="center" />
          <el-table-column prop="name" label="企业名称" min-width="200" :show-overflow-tooltip="true" align="center" />
          <el-table-column prop="nature" label="企业性质" min-width="200" :show-overflow-tooltip="true" align="center" :formatter="statusFormat" />
          <el-table-column prop="contacts" label="联系人" min-width="100" align="center" />
          <el-table-column
            prop="phone"
            label="联系电话"
            min-width="150"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column prop="enterpriseType" :formatter="(row) => formatterSysEnterpriseType(row)" label="企业类型" min-width="120" align="center" />
          <el-table-column label="企业状态" min-width="80" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.status === '0'">正常</span>
              <span v-if="scope.row.status === '1'">停用</span>
            </template>
          </el-table-column>
          <el-table-column label="审核状态" align="center" min-width="100" prop="checkStatus">
            <template slot-scope="scope">
              <span v-if="scope.row.checkStatus=== '0'">审核成功</span>
              <span v-if="scope.row.checkStatus=== '1'">审核失败</span>
              <span v-if="scope.row.checkStatus=== '2'">未审核</span>
              <span v-if="scope.row.checkStatus=== '3'">已初始化</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="createTime" label="创建时间" align="center" width="180" /> -->
        </el-table>

        <!-- 分页-->
        <pagination
          :total="total"
          :page.sync="filters.pageNum"
          :limit.sync="filters.pageSize"
          @pagination="getList"
        />
        <!-- 添加或修改对话框 -->
        <AddBasis ref="basisAdd" @childrenGetList="childrenGetList" />
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { listNoPermission } from '@/api/superviseBaseInfo/typeManage/organizationType'
import { mapState } from 'vuex'
import { listBasis, updateBasis, remove } from '@/api/enterprise/basis'
import AddBasis from './components/index'

import { listRegionTree } from '@/api/common/area'
import { getDicts } from '@/api/system-tool/dict/data'
// 引入高级设置一栏
// import HighLevelSetting from '@/components/HighLevelSetting'
export default {
  name: 'Basis',
  components: {
    AddBasis
  },
  data() {
    return {
      // 城市树是否显示
      fold: true,
      // 搜索城市名称表单
      cityName: '',
      // 城市树选中高亮
      currentColor: false,
      status: '0',
      // 企业列表树数据
      cityOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 搜索框
      filters: {
        province: '',
        city: '',
        area: '',
        status: '0',
        pageNum: 1,
        pageSize: this.fristPageSize,
        name: '',
        nature: '',
        enterpriseType: '2',
        legalperson: ''
      },
      sysEnterprise: {
        id: '',
        status: '',
        idNumber: ''
      },
      // 高级设置显示隐藏
      highLevelSet: false,
      // 时间范围
      dateRange: [],
      // 企业状态选项
      statusOptions: [],
      // 企业类型选项
      enterpriseTypeOptions: [{ dictValue: '', dictLabel: '全部' }],
      // 分页总条数
      total: 0,
      // 选中表格对话框的存储的值
      multipleSelection: [],
      selectRow: [],
      // 数据表格存放的数据
      tableData: [],
      // 表格加载是否显示等待图标
      tableLoading: false,
      // 修改按钮是否可用
      isAmend: true,
      isStatus: true,
      // 初始化弹框标识
      addOrUpdateVisible: false,
      // 父类中的方法传递到子页面
      natureData: []
    }
  },
  computed: {
    ...mapState({
      needTagsView: state => state.settings.tagsView
    }),
    // 高级搜索显示隐藏
    handleTagShow() {
      return this.highLevelSet
    }
  },
  watch: {
    cityName(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted: function() {
    this.getList()
  },
  created() {
    this.loadCityOptions()
    getDicts('sys_dept_status').then(resp => {
      this.statusOptions = resp.data.rows
    })
    getDicts('enterprise_type').then(resp => {
      this.enterpriseTypeOptions = { ...this.enterpriseTypeOptions, ...resp.data.rows }
    })
    this.getDicts('enterprise_nature').then(response => {
      this.natureData = response.data.rows
    })
  },
  methods: {
    // 获取单位类型
    async  listEnterpriseType() {
      const { data: { rows }} = await listNoPermission()
      this.EnterpriseType = rows
    },
    // 回显单位类型
    formatterSysEnterpriseType(row) {
      if (row && row.enterpriseType) {
        if (row.enterpriseType === '2') {
          return '监管单位'
        }
        if (this.EnterpriseType.length < 0) return
        const items = this.EnterpriseType.filter(item => {
          return item.typeNum === row.enterpriseType
        })
        return items.length > 0 ? items[0].typeName : '-'
      }
    },
    // 获取列表
    getList() {
      this.tableLoading = true
      listBasis(this.changeDateRange(this.filters, this.dateRange)).then(resp => {
        if (resp) {
          this.tableData = resp.data.rows
          this.total = resp.data.total
          this.tableLoading = false
          // this.addTaleData()
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // list表格填充空白行
    addTaleData() {
      if (this.tableData.length < this.fristPageSize) {
        const arr = {}
        this.tableData.push(arr)
        this.addTaleData()
      }
    },
    // 点击表格前面选框时触发的事件
    handleSelectionChange(val) {
      if (JSON.stringify(val[0]) === '{}') {
        this.$refs.multipleTable.clearSelection()
        val = []
      }
      this.multipleSelection = val
      this.isAmend = this.multipleSelection.length !== 1
      this.isStatus = this.multipleSelection.length !== 1
      if (this.multipleSelection.length === 1) {
        this.status = this.multipleSelection[0].status
      }
      this.selectRow = []
      if (val.length > 0) {
        val.forEach((item, index) => {
          this.selectRow.push(this.tableData.indexOf(item))
        })
      }
      if (val.length > 1) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(val.pop())
      }
    },

    // 单击每行时每行的复选框选中
    rowChecked(row) {
      const selectData = this.multipleSelection
      this.$refs.multipleTable.clearSelection()
      if (selectData.length === 1) {
        selectData.forEach(item => {	// 判断 如果当前的一行被勾选, 再次点击的时候就会取消选中
          if (item === row) {
            this.$refs.multipleTable.toggleRowSelection(row, false)
          } else {
            this.$refs.multipleTable.toggleRowSelection(row, true)
          }
        })
      } else {
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }
    },
    rowColor({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { 'background-color': 'rgba(185,211,249,0.75)' }
      }
    },
    // 项目状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.natureData, row.nature)
    },
    // 获取城市信息列表
    loadCityOptions() {
      listRegionTree().then(resp => {
        if (resp) {
          this.cityOptions = resp.data
        }
      })
    },
    // 搜索按钮
    handleQuery() {
      this.getList()
    },
    // 重置按钮
    resetQuery() {
      this.dateRange = []
      this.resetForm('topForm')
      this.filters.city = ''
      this.filters.province = ''
      this.$refs.tree.setCurrentKey()
      this.getList()
    },
    // 用户状态修改
    handleStatusChange() {
      const row = this.multipleSelection[0]
      const text = row.status === '0' ? '停用' : '启用'
      this.$confirm('确认要' + text + '' + row.name + '用户吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if (row.status === '0') {
            row.status = '1'
          } else {
            row.status = '0'
          }
          this.sysEnterprise.id = row.id
          this.sysEnterprise.status = row.status
          this.sysEnterprise.idNumber = row.idNumber
          updateBasis(this.sysEnterprise).then(resp => {
            if (resp) {
              this.getList()
              this.msgSuccess('操作成功！')
            } else {
              this.msgError(resp.message)
            }
          })
        })
        .catch(() => {
          this.msgInfo('已取消')
        })
    },
    // 点击添加菜单弹出的对话框
    handleAdd() {
      this.$refs.basisAdd.basisItemAdd()
    },
    // 编辑操作
    handleUpdate() {
      // 获取选中行的id
      if (this.multipleSelection.checkStatus === '0') {
        this.msgInfo('企业审核成功，无法修改')
      } else {
        // 主键
        const id = this.multipleSelection[0].id
        this.$refs.basisAdd.basisItemUpdate(id)
      }
    },
    // 删除
    handleDelete() {
      // 获取选中行的id
      const child = this.multipleSelection
      this.$confirm('确认要删除此企业吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          this.loading = true
          let ids = ''
          for (let i = 0; i < child.length; i++) {
            ids += child[i].id + ','
          }
          // 去掉最后一个逗号
          if (ids.length > 0) {
            ids = ids.substr(0, ids.length - 1)
          }
          const data = {
            ids: ids
          }
          remove(data).then(resp => {
            this.loading = false
            if (resp) {
              this.msgSuccess('删除成功！')
              // 重新加载表格数据
              this.getList()
            } else {
              this.msgError(resp.message)
            }
          })
        })
        .catch(() => {})
    },
    // 企业树形数据筛选
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.filters.province = ''
      this.filters.city = ''
      this.filters.area = ''
      const { count } = data
      switch (count) {
        case 0:
          this.filters.province = data.value
          break
        case 1:
          this.filters.city = data.value
          break
        case 2:
          this.filters.area = data.value
          break
      }
      this.$nextTick(() => {
        this.currentColor = true // 使树筛选时选中的节点高亮显示
        this.$refs.tree.setCurrentKey(data.value)
      })
      this.getList()
    },
    toggleSelection() {
      this.$refs.multipleTable.clearSelection()
    },
    childrenGetList() {
      this.getList()
      this.loadCityOptions()
    },
    // 获取高级设置中子组件传递的数据
    getValueFromChild(data) {
      this.highLevelQueryParams = data
    }
  }
}
</script>
